package com.woniu.product.listener;

import com.alibaba.fastjson2.JSONObject;
import com.rabbitmq.client.Channel;
import com.woniu.product.service.TOrderService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

import static com.woniu.common.constant.MqConstant.Queue.*;

/**
 * @author sw
 * @Description
 */
@Slf4j
@Component
public class JiFenListener {

    @Autowired
    private TOrderService orderService;

    @Autowired
    private StringRedisTemplate redisTemplate;


    @SneakyThrows
    @RabbitListener(queues = JIFEN_QUEUE)
    public void addRechargeOrder(String msg, Message message, Channel channel) {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        String messageId = message.getMessageProperties().getMessageId();
        try {
            Boolean delete = redisTemplate.delete("message:" + messageId);
            if (delete) {
                JSONObject jsonObject = JSONObject.parseObject(msg, JSONObject.class);
                //把参数拿出来
                String phone = jsonObject.getString("phone");
                Integer integral = jsonObject.getInteger("integral");
                Long orderNum = jsonObject.getLong("orderNum");
                //处理业务，下单：生产订单数据
                orderService.addJifenRechargeOrder(phone, integral, orderNum);
            }
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error("addRechargeOrder error:{}", e);
            redisTemplate.opsForValue().set(messageId, messageId, 30, TimeUnit.MINUTES);
            //拒绝签收并不保留消息，之道死信
            channel.basicReject(deliveryTag, false);
        }

    }

    @SneakyThrows
    @RabbitListener(queues = DLX_TTL_JIFEN_QUEUE)
    public void rollbackRechargeOrder(String msg, Message message, Channel channel) {
        JSONObject jsonObject = JSONObject.parseObject(msg, JSONObject.class);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            //把参数拿出来
            String phone = jsonObject.getString("phone");
            Integer integral = jsonObject.getInteger("integral");
            Long orderNum = jsonObject.getLong("orderNum");

            //处理业务,回滚订单
            orderService.rollbackJifenRechargeOrder(orderNum, phone, integral);

            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error("rollbackRechargeOrder error:{}", e);
            //拒绝签收并不保留消息
            channel.basicReject(deliveryTag, false);
//            channel.basicNack(deliveryTag,false,false);
        }
    }
}
